package com.jyx.auth.controller;

import com.jyx.api.oauth.AuthControllerApi;
import com.jyx.auth.service.AuthService;
import com.jyx.framework.domain.ucenter.ext.AuthToken;
import com.jyx.framework.domain.ucenter.request.RegisterRequest;
import com.jyx.framework.domain.ucenter.response.AuthCode;
import com.jyx.framework.domain.ucenter.response.JwtResult;
import com.jyx.framework.domain.ucenter.response.LoginResult;
import com.jyx.framework.exception.ExceptionCast;
import com.jyx.framework.model.response.CommonCode;
import com.jyx.framework.model.response.ResponseResult;
import com.jyx.framework.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class AuthController implements AuthControllerApi {

    @Value("${auth.clientId}")
    String clientId;
    @Value("${auth.clientSecret}")
    String clientSecret;
    @Value("${auth.cookieDomain}")
    String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    int cookieMaxAge;
    @Value("${auth.tokenValiditySeconds}")
    int tokenValiditySeconds;
    @Autowired
    AuthService authService;

    @Override
    @PostMapping("/userlogin")
    public LoginResult login(LoginResult loginResult,HttpServletResponse response) {
        if(loginResult == null || StringUtils.isEmpty(loginResult.getUsername())){
            ExceptionCast.cast(AuthCode.AUTH_USERNAME_NONE);
        }
        if(StringUtils.isEmpty(loginResult.getPassword())){
            ExceptionCast.cast(AuthCode.AUTH_PASSWORD_NONE);
        }
        AuthToken loginAuth = authService.login(loginResult.getUsername(), loginResult.getPassword(), clientId, clientSecret);
        //CookieUtil.addCookie(response, "ucenter.jieyouxiang.com", "/", "uid", null, 0, false);
        String access_token = loginAuth.getAccess_token();

        saveCookie(response,access_token);
        return new LoginResult(CommonCode.SUCCESS,access_token);
    }


    private void saveCookie(HttpServletResponse response,String access_token) {
        //HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","uid",access_token,cookieMaxAge,false);//这个false表示允许浏览器访问

    }

    @Override
    @PostMapping("/userlogout")
    public ResponseResult logout(HttpServletRequest request) {
        String uid = getTokenFromCookie(request);
        authService.delToken(uid);
        clearCookie(uid);

        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @PostMapping("/userRegister")
    public ResponseResult register(@RequestBody RegisterRequest registerRequest) {
        return authService.register(registerRequest);
    }

    private void clearCookie(String uid) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", uid, 0, false);
    }

    @Override
    @GetMapping("/userjwt")
    public JwtResult userJwt(HttpServletRequest request) {
        //获取cookie中的令牌
        String access_token = getTokenFromCookie(request);
        //根据令牌从redis中查询jwt
        AuthToken authToken = authService.getUserToken(access_token);
        if(authToken == null){
            System.out.println("获取令牌为空~！");
            return new JwtResult(CommonCode.FAIL, null);
        }
        return new JwtResult(CommonCode.SUCCESS,authToken.getJwt_token());
    }

    private String getTokenFromCookie(HttpServletRequest request) {
       // HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
        String access_token = cookieMap.get("uid");
        return access_token;
    }
}
